package com.yanxu.bio.V2.client;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2024/12/21-2024
 * @Description: bio 客户端
 */
public class ChatClient {

    Socket socket = null;

    public void start() {
        try {
            //主线程： 与服务端建立连接
            socket = new Socket("127.0.0.1", 8080);
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            //创建一个新的线程，处理用户的键盘输入，将消息发送给服务端。
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
                        while (true) {
                            //将键盘输入的消息发送给服务端。
                            String s = consoleReader.readLine();
                            writer.write(s + "\n");
                            writer.flush();


                            //判断用户是否要退出了
                            // 当用户输入 "quit", 表示用户要退出了，因此 break 退出循环，子线程结束即可。
                            if (s.equals("quit")) {
                                break;
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();

            //主线程接受服务端发送过来的消息
            String msg = null;
            while ((msg = reader.readLine()) != null) {
                System.out.println(msg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        chatClient.start();
    }
}